package com.milo.coding.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @Auther milo
 * @Description
 * @Date 2021-01-17 23:03
 */
public class ChatServerHandler extends ChannelInboundHandlerAdapter {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String welcome = channel.remoteAddress() + " 进入聊天室";
        channelGroup.add(channel);
        for (Channel item : channelGroup) {
            item.writeAndFlush(welcome);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String quit = channel.remoteAddress() + " 退出聊天室";
        channelGroup.remove(channel);
        for (Channel item : channelGroup) {
            item.writeAndFlush(quit);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        for (Channel item : channelGroup) {
            if(!channel.remoteAddress().equals(item.remoteAddress())){
                String message = "[" + channel.remoteAddress() + "]: " + (String) msg;
                item.writeAndFlush(message);
            }
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
